package com.sbio.udiapp.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.sbio.udiapp.R;
import com.sbio.udiapp.adapter.PackingListViewAdapter;
import com.sbio.udiapp.common.bean.OutStockVo;
import com.sbio.udiapp.databinding.ActivityOutStockBinding;
import com.sbio.udiapp.net.api.ApiService;
import com.sbio.udiapp.net.exception.ErrorComsumerSupplier;
import com.sbio.udiapp.net.exception.ErrorConsumerAdapter;
import com.sbio.udiapp.net.response.ResponseTransformer;
import com.sbio.udiapp.util.CollectionUtils;
import com.sbio.udiapp.util.DialogUtil;
import com.sbio.udiapp.util.EventUtil;
import com.sbio.udiapp.util.ToastUtil;
import com.sbio.udiapp.util.ViewUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class OutStockActivity extends AppCompatActivity implements View.OnClickListener {

    private ActivityOutStockBinding binding;

    @Inject
    ApiService apiService;

    //为listView装载数据
    List<String> datas = new ArrayList<>();

    private PackingListViewAdapter packingListViewAdapter;

    public static String getUnicode(String string) {
        char[] chars = "　".toCharArray();
        String str = "";
        for (int i = 0; i < chars.length; i++) {
            str = "\\u" + Integer.toString(chars[i], 16);
        }
        return str;
    }

    @SuppressLint("RestrictedApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityOutStockBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());


        /*binding.outStockNumber.setInputType(InputType.TYPE_NULL);
        binding.outStockNumber.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                //隐藏键盘
                ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE))
                        .hideSoftInputFromWindow(OutStockActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }

        });*/
        //为出库单号输入框添加回车事件

        binding.outStockNumber.setOnEditorActionListener((v, actionId, event) -> checkOutStockNoExist());
        binding.outStockNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    checkOutStockNoExist();
                }
            }
        });
//        binding.etPbNo.setInputType(InputType.TYPE_NULL);
//        binding.etPbNo.setOnFocusChangeListener((v, hasFocus) -> {
//            if (hasFocus) {
//                //隐藏键盘
//            ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE))
//                    .hideSoftInputFromWindow(OutStockActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//            }
//
//        });
//        binding.etPbNo.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(OutStockActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//            }
//        });
        //为编码输入框添加回车事件
        binding.etPbNo.setOnEditorActionListener((v, actionId, event) -> {
            String outStockNo = binding.outStockNumber.getText().toString();
            if (TextUtils.isEmpty(outStockNo)) {
                DialogUtil.showCommonAlertDialog("请先输入出库单号");
                v.setText("");
                //获取焦点
                ViewUtil.requestFocus(v);
                return false;
            }
            String pbNo = v.getText().toString();
            if (datas.contains(pbNo)) {
                binding.etPbNo.setText("");
                //弹出提示框
                DialogUtil.showCommonAlertDialog("数据重复，输入框已清空");
                return false;
            }
            //校验箱码盒码是否存在，是否已经在其他出库单出库
            apiService.checkPbNo(outStockNo,pbNo)
                    .compose(ResponseTransformer.obtain())
                    .subscribe(ajaxResult -> {
                            /*if (ajaxResult.getData(Boolean.class)) {
                                //校验通过，添加pbNo
                                datas.add(pbNo);
                                v.setText("");
                                //获取焦点
                                ViewUtil.requestFocus(v);
                                packingListViewAdapter.notifyDataSetChanged();
                                return;
                            }*/

                        //校验通过，添加pbNo
                        datas.add(pbNo);
                        ToastUtil.showLong("添加成功");
                        v.setText("");
                        //获取焦点
                        ViewUtil.requestFocus(v);
                        packingListViewAdapter.notifyDataSetChanged();
                        return;
                        //校验不通过
                        //清空数据
//                            v.setText("");
//                            //弹出错误框
//                            DialogUtil.showCommonAlertDialog(ajaxResult.getMsg());

                    }, ErrorComsumerSupplier.of(apiException -> {
                        DialogUtil.showCommonAlertDialog(apiException.getErrMsg());
                        v.setText("");
                        ViewUtil.requestFocus(binding.etPbNo);
                    }));
            return false;
        });
        //新建Adapter
        packingListViewAdapter = new PackingListViewAdapter(this, binding.etPbNo, datas);
        //为ListView设置Adapter
        binding.lvBoxCode.setAdapter(packingListViewAdapter);
        //出库按钮绑定事件
        binding.btnOutStock.setOnClickListener(this);
        binding.outStockNumber.requestFocus();
    }

    private boolean checkOutStockNoExist() {
        //1.校验出库单是否存在，不存在则清空出库单号
        //2.出库单已经出库，则进行反出库（列出所有已出库的箱盒码）
        String outStockNo = binding.outStockNumber.getText().toString();
        if (TextUtils.isEmpty(outStockNo)) {
            return true;
        }
        apiService.checkOutStockCanOut(outStockNo)
                .compose(ResponseTransformer.obtain())
                .subscribe(ajaxResult -> {
                    OutStockVo outStockVo = ajaxResult.getData(OutStockVo.class);
                    if (outStockVo == null) {
                        return;
                    }
                    datas.addAll(outStockVo.getNos());
                }, ErrorComsumerSupplier.of((apiException) -> {
                    DialogUtil.showCommonAlertDialog(apiException.getErrMsg());
                    binding.outStockNumber.setText("");
                    ViewUtil.requestFocus(binding.outStockNumber);
                }));

        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_out_stock:
                String outStockNo = binding.outStockNumber.getText().toString();
                if (TextUtils.isEmpty(outStockNo)) {
                    DialogUtil.showCommonAlertDialog("出库单号不能为空");
                    return;
                }
                if (CollectionUtils.isEmpty(datas)) {
                    DialogUtil.showCommonAlertDialog("箱码盒码不能为空");
                    return;
                }
                OutStockVo outStockVo = new OutStockVo(outStockNo, datas);
                apiService.outStock(outStockVo)
                        .compose(ResponseTransformer.obtain())
                        .subscribe(ajaxResult -> {
                            if (ajaxResult.isSuccess()) {
                                ToastUtil.show("出库成功");
                                binding.outStockNumber.setText("");
                                datas.clear();
                                packingListViewAdapter.notifyDataSetChanged();
                            } else {
                                DialogUtil.showCommonAlertDialog(ajaxResult.getMsg());
                            }
                        }, new ErrorConsumerAdapter());

                break;
        }
    }
}